package jdbc1;

import java.sql.*;

/**
 * @author oldliu
 * @since 1.0
 */
public class BankTransfer {
    static {
        try {
            //static{}执行了
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();

        }
    }

    public static void main(String[] args) {
        transfer("laoma","xiaowu",100000);
    }

    public static boolean transfer(String from, String to, int money) {
        String url = "jdbc:mysql://localhost:3308/java83?useUnicode=true&characterEncoding=utf8&useSSL=false" +
                "&serverTimezone=Asia/Shanghai";
        Connection con=null;
        PreparedStatement ps=null;
        String sql="update bank set balance=balance-? where acno=?";
        //String sql="update bank set balance=balance+? where acno=?";
        try {
            con = DriverManager.getConnection(url, "xukang", "Xu1234");
            con.setAutoCommit(false);//!!!!
            ps = con.prepareStatement(sql);
            ps.setInt(1,money);
            ps.setString(2,from);
            int r1=ps.executeUpdate();
            ps.close();
            ps=con.prepareStatement(sql);
            ps.setInt(1,-money);
            ps.setString(2,to);
            int r2=ps.executeUpdate();
            if(r1*r2==1){
                con.commit();
                return true;
            }else{
                con.rollback();
            }
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return false;
    }
}
